import MyTimePicker from "./MyTimePicker";
import MyWeekPicker from "./MyWeekPicker";
import {Button, Icon, Popconfirm} from "antd";
import React, {useCallback, useEffect, useMemo, useState} from "react";
import {deleteBroadCase, getBroadCast, patchBroadCast, postBroadCast} from "../../../../api/broadcast";

function MyTable({head, channelUrl, channelId, type}) {
	// let lastArr = []

	//处理多选框 每日与各个选项之间的关系
	function processWeek(result) {
		//如果有*代表该次选择包括每日，然后根据lastArr判断*是当前选中还是上次选中
		if (result.indexOf("*") > -1) {
			if (lastArr.length == 1 && lastArr[0] == "*") {
				result.splice(result.length - 1, 1)
			} else {
				result.splice(0, result.length - 1,)
			}
		} else {
			//如果全选则自定选中每天
			if (result.length == 7) {
				console.log(result.length)
				result = ["*"]
			}
		}
		// lastArr = result
		setLastArr(result)
		return result
	}

	function joinCron(cron, week) {
		return cron + " * * " + week.join(",")
	}


	function testCron(cron) {
		const standCron = /\d{0,2}\s\d{0,2}\s\*\s\*\s(\*{1}|(\d,*))*/
		return standCron.test(cron)
	}

	function setPageData() {

		getBroadCast({channelId, schedule_type: type}).then(res => {
			if (res.count > 0) {
				const list = res.results.map((item, index) => {
					const cronStartArr = item.start_crontab.split(' ')
					const cronEndArr = item.end_crontab.split(' ')
					return {
						id: item.id,
						cronStart: `${cronStartArr[0]} ${cronStartArr[1]}`,
						cronEnd: `${cronEndArr[0]} ${cronEndArr[1]}`,
						week: cronStartArr[cronStartArr.length - 1].split(","),
						locked: true
					}
				})
				setTimeList(list)
			} else {
				setTimeList([])
			}
		})
	}


	const [timeList, setTimeList] = useState([])
	const [lastArr, setLastArr] = useState([])
	const [reRender, setReRender] = useState(true)

	const setLocked = useCallback((index) => () => {
			const time = timeList[index]
			time.locked = !time.locked
			timeList.splice(index, 1, time)
			setTimeList([...timeList])
			setLastArr(time.week)
			if (time.locked) {
				const startCron = joinCron(time.cronStart, time.week)
				const endCron = joinCron(time.cronEnd, time.week)
				if (testCron(startCron) && testCron(endCron)) {
					if (time.id) {
						patchBroadCast({
							id: time.id,
							channel: channelUrl,
							start_crontab: startCron,
							end_crontab: endCron,
							schedule_type: type
						}).then(res => {
							setPageData()
						})
					} else {
						postBroadCast({
							channel: channelUrl,
							start_crontab: startCron,
							end_crontab: endCron,
							schedule_type: type
						}).then(() => {
							setPageData()
						})
					}
				}
			}
		}, [timeList, lastArr]
	)


	const setTime = useCallback(({index, id, timeCron, item}) => {
		const time = item
		time[id] = timeCron
		timeList.splice(index, 1, time)
		setTimeList([...timeList])
	}, [timeList])

	const setWeek = useCallback(({index, weekCron, item}) => {
		const week = item
		week['week'] = processWeek(weekCron)
		timeList.splice(index, 1, week)
		setTimeList([...timeList])
	}, [timeList])


	useEffect(() => {
		setPageData()
	}, [channelUrl, channelId, type])

	return (
		<table border={1} width={640} style={{textAlign: "center", border: '1px solid #ccc'}}>
			<thead>
			<tr style={{background: '#f0f2f5'}}>
				<th colSpan={2} width={560} style={{padding: '10px 0', fontSize: '16px'}}>
					{head}
				</th>
				<th width={80}>
					操作
				</th>
			</tr>
			</thead>
			<tbody>

			{
				timeList.map((item, index) => {
					return (
						<tr key={index}>
							<td>
								<MyTimePicker
									disabled={item.locked}
									initTime={item.cronStart}
									getTime={setTime}
									item={item}
									id={'cronStart'}
									index={index}/>
								~
								<MyTimePicker
									disabled={item.locked}
									initTime={item.cronEnd}
									getTime={setTime}
									item={item}
									id={'cronEnd'}
									index={index}/>
							</td>
							<td style={{padding: '5px'}}>
								<MyWeekPicker
									disabled={item.locked}
									initWeek={item.week}
									index={index}
									item={item}
									getWeek={setWeek}
								/>
							</td>
							<td width={80}>
								<Icon style={{fontSize: '20px'}} type={item.locked ? 'lock' : 'unlock'}
								      onClick={setLocked(index)}/>
								<Popconfirm
									title="确定删除吗?"
									onConfirm={() => {
										// console.log(item)
										if (item.id) {
											deleteBroadCase(item.id).then((res) => {
												setPageData()
											})
										} else {
											setTimeList([])
										}
									}}>
									<Icon style={{fontSize: '20px', marginLeft: '10px'}} type={'delete'}/>
								</Popconfirm>

							</td>
						</tr>
					)
				})
			}
			<tr>
				<td colSpan={3}>
					<Button style={{width: '100%'}} onClick={() => {
						setTimeList([...timeList, {
							week: [],
							cronStart: "",
							cronEnd: "",
							locked: true
						}])
					}}>

						<Icon type="plus"/></Button>
				</td>
			</tr>
			</tbody>
		</table>
	)
}

export default React.memo(MyTable)
